package sf01.studentmngmsystem.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import sf01.studentmngmsystem.entity.Student;
import sf01.studentmngmsystem.service.StudentService;
import jakarta.servlet.http.HttpSession;
import java.time.format.DateTimeFormatter;

@Controller
public class LoginController {
    
    @Autowired
    private StudentService studentService;
    
    // 显示登录页面
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }
    
    // 处理登录请求
    @PostMapping("/login")
    public String login(@RequestParam String account, 
                       @RequestParam String password, 
                       HttpSession session, 
                       Model model) {
        try {
            // 验证登录
            Student student = studentService.login(account, password);
            if (student != null) {
                // 登录成功，保存学生信息到session
                session.setAttribute("student", student);
                session.setAttribute("studentId", student.getId());
                // 重定向到学生个人主页
                return "redirect:/student/profile?id=" + student.getId();
            } else {
                model.addAttribute("error", "账号或密码错误");
                return "login";
            }
        } catch (Exception e) {
            model.addAttribute("error", "登录失败：" + e.getMessage());
            return "login";
        }
    }
    
    // 注销登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }

}